package com.yanyeori.framework.core.model;

import com.yanyeori.framework.core.util.ServletUtil;
import com.yanyeori.framework.core.util.StringUtil;
import lombok.*;

import java.io.Serializable;

/**
 * 分页参数
 *
 * @author chenkuan
 * @since 2022/8/8
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class PageParam implements Serializable {
    private static final long serialVersionUID = 1L;

    //页码
    private int pageNum;
    //每页显示记录数
    private int pageSize;
    //排序字段
    private String sortField;
    //排序方式
    private String sortOrder;
    //分页参数合理化
    private Boolean reasonable;

    public String getOrderBy() {
        if (StringUtil.isEmpty(sortField)) return null;
        return StringUtil.toUnderlineCase(sortField) + " " +
                ("descending".equalsIgnoreCase(sortOrder) || "desc".equalsIgnoreCase(sortOrder) ? "desc" : "asc");
    }

    public static PageParam buildRequestPage() {
        PageParam pageParam = new PageParam();
        pageParam.setPageNum(ServletUtil.getIntParameter("pageNum", 1));
        pageParam.setPageSize(ServletUtil.getIntParameter("pageSize", 10));
        pageParam.setSortField(ServletUtil.getParameter("sortField"));
        pageParam.setSortOrder(ServletUtil.getParameter("sortOrder", "asc"));
        pageParam.setReasonable(ServletUtil.getBooleanParameter("reasonable"));
        return pageParam;
    }
}
